<?php
// +----------------------------------------------------------------------
// | 导出CSV文件
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2017 http://www.yii2cms.com All rights reserved.
// +----------------------------------------------------------------------
// | Time  : 2017/07/03
// +----------------------------------------------------------------------
namespace app\extensions;

use Yii;

class XCsv
{
    public $fileHandle; // 句柄
    public $fileName; // 文件名
    public $savePath; // 文件保存路径
    public $separator; // CSV文件的分隔符

    /**
     * 构造函数
     * @param array $config default array() 配置参数
     * @return none
     */
    public function __construct($config = [])
    {
        if (empty($config)) {
            $this->fileName  = time();
            $this->savePath  = Yii::getAlias('@runtime') . '/';
            $this->separator = '';
        } else {
            $this->fileName  = $config['fileName'] ? $config['fileName'] : time();
            $this->savePath  = $config['savePath'] ? $config['savePath'] : Yii::getAlias('@runtime') . '/';
            $this->separator = $config['separator'] ? $config['separator'] : '';
        }

        $this->savePath = '/' . trim($this->savePath, '/') . '/';
    }

    /**
     * 设置表头，只能插入一行
     * @param array $row
     * @return
     */
    public function setHeader($row)
    {
        $this->fileHandle = fopen($this->savePath . $this->fileName . '.csv', 'w');
        $row              = array_map([__CLASS__, 'utf8ToGbk'], $row);

        fputcsv($this->fileHandle, $row);
        fclose($this->fileHandle);
    }

    /**
     * 在文件添加数据（覆盖原来的内容）
     * @param
     * @return
     */
    public function addRows($data)
    {
        $this->fileHandle = fopen($this->savePath . $this->fileName . '.csv', 'w');
        foreach ($data as $row) {
            $row = array_map([__CLASS__, 'utf8ToGbk'], $row);
            fputcsv($this->fileHandle, $row);
        }
        fclose($this->fileHandle);
    }

    /**
     * 在文件末尾追加数据（保留原来的内容）
     * @param
     * @return
     */
    public function appendRows($data)
    {
        $this->fileHandle = fopen($this->savePath . $this->fileName . '.csv', 'a');
        foreach ($data as $row) {
            $row = array_map([__CLASS__, 'utf8ToGbk'], $row);
            fputcsv($this->fileHandle, $row);
        }
        fclose($this->fileHandle);
    }

    /**
     * 下载CSV文件
     * @param bool $isDelete default true 是否删除文件
     * @return none
     */
    public function download($isDelete = true)
    {
        header('Content-type:text/csv');
        header('Content-Disposition:attachment;filename="' . $this->fileName . '.csv' . '"');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $fileFullPath = $this->savePath . $this->fileName . '.csv';

        $data = file_get_contents($fileFullPath);

        if ($isDelete) {
            // 删除文件
            if (is_readable($fileFullPath) == false) {
                die('文件不存在或者无法读取');
            } else {
                if (!unlink($fileFullPath)) {
                    echo('文件无法删除');
                }
            }
        }

        echo $data;
    }

    /**
     * 将字符串的编码由UTF-8转为GB2312
     * @param string $str must 要转码的字符串
     * @return 转码后的字符串
     */
    public function utf8ToGbk($str)
    {
        return iconv('UTF-8', 'GB2312//IGNORE', $str);
    }

    /**
     * 析构函数
     * @param none
     * @return none
     */
    public function __destruct()
    {
        // exit();
    }
}
